﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.UI.WebControls;
using System.IO;

namespace MediaMonitor.Common
{



    /// <summary>
    /// Summary description for Utility
    /// </summary>
    public class Utility
    {
        public Utility()
        {
        }


        public static string AppPath
        {
            get
            {
                //return ConfigurationManager.AppSettings["AppPath"].ToString();
                return GetAppPath();
            } 
        }

       


        public static string AppName
        {
            get
            {
                return ConfigurationManager.AppSettings["AppName"].ToString();
            }

        }

        public static string GetAppPath()
        {
            //return ConfigurationManager.AppSettings("AppPath");
            string Port = HttpContext.Current.Request.Url.Port.ToString();
            string Protocol = HttpContext.Current.Request.Url.Scheme;
            string BasePath = "";

            if ((Port == null || Port == "80" || Port == "443"))
            {
                Port = "";
            }
            else
            {
                Port = ":" + Port;
            }


            if ((Protocol == null || Protocol == "http"))
            {
                Protocol = "http://";
            }
            else
            {
                Protocol = "https://";
            }


            BasePath = Protocol + HttpContext.Current.Request.Url.Host + Port + HttpContext.Current.Request.ApplicationPath;
            BasePath = BasePath.TrimEnd('/');
            return BasePath.Substring(0, BasePath.Length);
        }


        public static byte DefaultCountry
        {
            get { 
                ////return Utility.ToByte(ConfigurationManager.AppSettings["DefaultCountry"]); 
                
                if(HttpContext.Current.Session!=null)
                   if (HttpContext.Current.Session["UserCountryID"] != null)
                          return Utility.ToByte(HttpContext.Current.Session["UserCountryID"]);

                if (HttpContext.Current.Request.Url.Host.ToLower().Contains(".do"))
                    return Utility.ToByte(58);
                if (HttpContext.Current.Request.Url.Host.ToLower().Contains(".pr"))
                    return Utility.ToByte(177);
                if (HttpContext.Current.Request.Url.Host.ToLower().Contains(".tt"))
                    return Utility.ToByte(218);
                if (HttpContext.Current.Request.Url.Host.ToLower().Contains(".ve"))
                    return Utility.ToByte(231);

                return Utility.ToByte(ConfigurationManager.AppSettings["DefaultCountry"]);
            }

        }

        #region General Functions

        public static string GetYesNo(bool val)
        {
            return val ? "yes" : "<span style='color:red'>No</span>";
        }

        public static string GetFormattedBool(bool val, string trueText, string falseText)
        {
            return val ? trueText : falseText;
        }
        

        public static string LPad(string str, string fillChar, int digits)
        {
            if (str.Length <= digits)
            {
                for (int i = 0; i < digits - str.Length; i++)
                    str = fillChar + str;

                //do nothing
            }

            return str;
        }

        public static string GetUniqueCode()
        {
            DateTime d = DateTime.UtcNow;
            string dd = LPad(d.Day.ToString(), "0", 2);
            string mm = LPad(d.Month.ToString(), "0", 2);
            string yyyy = d.Year.ToString();
            string hh = LPad(d.Hour.ToString(), "0", 2);
            string min = LPad(d.Minute.ToString(), "0", 2);
            string ss = LPad(d.Second.ToString(), "0", 2);
            string ms = d.Millisecond.ToString();

            return yyyy + mm + dd + hh + min + ss;

        }

        public static string GetUniqueCode_Short()
        {
            DateTime d = DateTime.UtcNow;
            string dd = LPad(d.Day.ToString(), "0", 2);
            string mm = LPad(d.Month.ToString(), "0", 2);
            string yyyy = d.Year.ToString();

            return yyyy + mm + dd;
        }

        #endregion

        #region DataType Conversion

        #region Date Conversion

        public static DateTime ToDateTime(Object val)
        {
            if (val == null)
                return DateTime.MinValue;

            DateTime dt;
            return DateTime.TryParse(val.ToString(), out dt) ? dt : DateTime.MinValue;
        }

        public static DateTime ToDateTime(Object val, string alternateVal)
        {
            if (val == null)
                return DateTime.MinValue;

            DateTime dt;
            return DateTime.TryParse(val.ToString(), out dt) ? dt : Convert.ToDateTime(alternateVal);
        }

        public static DateTime ToDateTime(Object val, DateTime alternateVal)
        {
            if (val == null)
                return DateTime.MinValue;

            DateTime dt;
            return DateTime.TryParse(val.ToString(), out dt) ? dt : alternateVal;
        }


        #endregion

        #region Strings

        public static string ToStr(Object val)
        {
            return val == null ? "" : val.ToString();
        }


        #endregion

        #region Numbers 

        public static int ToInt(Object val, int alternateVal)
        {
            int i;
            return int.TryParse(Utility.ToStr(val), out i) ? i : alternateVal;
        }

        public static int ToInt(Object val)
        {
            int i;
            return int.TryParse(Utility.ToStr(val) , out i) ? i : 0;
        }

        public static Int16 ToInt16(Object val, Int16 alternateVal)
        {
            Int16 i;
            return Int16.TryParse(Utility.ToStr(val), out i) ? i : alternateVal;
        }

        public static Int16 ToInt16(Object val)
        {
            Int16 i;
            return Int16.TryParse(Utility.ToStr(val), out i) ? i : Convert.ToInt16(0);
        }

        public static Int32 ToInt32(Object val, Int32 alternateVal)
        {
            Int32 i;
            return Int32.TryParse(Utility.ToStr(val), out i) ? i : alternateVal;
        }

        public static Int32 ToConvertInt32(Object val)
        {
            Int32 i;
            return Int32.TryParse(Utility.ToStr(val), out i) ? i : 0;
        }


        public static Int64 ToInt64(Object val, Int64 alternateVal)
        {
            Int64 i;
            return Int64.TryParse(Utility.ToStr(val), out i) ? i : alternateVal;
        }

        public static Int64 ToInt64(Object val)
        {
            Int64 i;
            return Int64.TryParse(Utility.ToStr(val), out i) ? i : Convert.ToInt64(0);
        }

        public static Double ToDouble(Object val)
        {
            Double dbl;
            return Double.TryParse(Utility.ToStr(val), out dbl) ? dbl : 0.0;
        }

        public static float Tofloat(Object val)
        {
            float fl;
            return float.TryParse(Utility.ToStr(val), out fl) ? fl : (float)0.0;
        }

        public static Decimal ToDecimal(Object val)
        {
            Decimal dec;
            return Decimal.TryParse(Utility.ToStr(val), out dec) ? dec : (Decimal)0.0;
        }

        #endregion

        #region Boolean

        public static Boolean ToBool(Object val)
        {
            bool b;
            return bool.TryParse(Utility.ToStr(val), out b) ? b : false;
        }

        public static Boolean ToBool(Object val, bool alternateVal)
        {
            bool b;
            return bool.TryParse(Utility.ToStr(val), out b) ? b : alternateVal;
        }


        #endregion

        #region Byte

        public static byte ToByte(Object val, byte alternateVal)
        {
            byte i;
            return byte.TryParse(Utility.ToStr(val), out i) ? i : alternateVal;
        }

        public static byte ToByte(Object val)
        {
            byte i;
            return byte.TryParse(Utility.ToStr(val), out i) ? i : (byte)(0);
        }

        #endregion

        #endregion

        #region Null Values


        public static int IsNullInt(Object val)
        {
            if (val == null || val.ToString() == DBNull.Value.ToString())
                return 0;
            else
                return Convert.ToInt32(val);
        }


        public static Object IsNull(Object val, Object defaultVal)
        {
            if (val == null || val.ToString() == DBNull.Value.ToString())
                return defaultVal;
            else
                return val;
        }

        public static String IsNullStr(Object val)
        {
            if (val == null || val.ToString() == DBNull.Value.ToString())
                return "";
            else
                return val.ToString();
        }

        public static String IsNullStr(Object val, string defaultVal)
        {
            if (val == null || val.ToString() == DBNull.Value.ToString())
                return defaultVal;
            else
                return val.ToString();
        }

        public static Boolean IsNullBool(Object val, Boolean defaultVal)
        {
            if (val == null || val.ToString() == DBNull.Value.ToString())
                return defaultVal;
            else
                return Convert.ToBoolean(val);
        }

        public static Boolean IsNullBool(Object val)
        {
            if (val == null || val.ToString() == DBNull.Value.ToString())
                return false;
            else
                return Convert.ToBoolean(val);
        }

        public static DateTime IsNullDate(Object val, DateTime defaultVal)
        {
            if (val == null || val.ToString() == DBNull.Value.ToString())
                return defaultVal;
            else
                return Convert.ToDateTime(val);
        }


        public static DateTime IsNullDate(Object val)
        {
            if (val == null || val.ToString() == DBNull.Value.ToString())
                return DateTime.MinValue;
            else
                return Convert.ToDateTime(val);
        }


        public static decimal IsNullDec(Object val)
        {
            if (val == null || val.ToString() == DBNull.Value.ToString())
                return 0;
            else
                return Convert.ToDecimal(val);
        }

        #endregion

        #region Dates

        public static DateTime GetDateFromNumber(string number)
        {
            //i-e: number = 20101231
            number = number.Replace(" ", "");
            string d = number;

            if(number.Length>=6)
                d = number.Substring(4, 2).Trim() + "/" + number.Substring(6, 2).Trim() + "/" + number.Substring(0, 4).Trim();
                //for local
              //d = number.Substring(6, 2).Trim() + "/" + number.Substring(4, 2).Trim() + "/" + number.Substring(0, 4).Trim();
            return Convert.ToDateTime(d);
        }
        public static DateTime GetDateNewsAlertFromNumber(string number)
        {
            //i-e: number = 20101231
            number = number.Replace(" ", "");
            string d = number;

            if (number.Length >= 6)
                d = number.Substring(4, 2).Trim() + "/" + number.Substring(6, 2).Trim() + "/" + number.Substring(0, 4).Trim() + " " + number.Substring(8, 2).Trim() + ":" + number.Substring(10, 2).Trim();
            //for local
             //d = number.Substring(6, 2).Trim() + "/" + number.Substring(4, 2).Trim() + "/" + number.Substring(0, 4).Trim();
            
            return Convert.ToDateTime(d);
        }

        public static string GetDateDDMMYYY(string dt)
        {

            string part1;
            string part2;
            string part3;

            if (dt == "") return "";

            dt = dt.Contains(" ") ? dt.Substring(0, dt.IndexOf(" ")) : dt;
            dt = dt.Trim();

            part1 = LPad(dt.Substring(0, dt.IndexOf("/")), "0", 2);
            part2 = LPad(dt.Substring(dt.IndexOf("/") + 1, 2).Replace("/", ""), "0", 2);
            part3 = LPad(dt.Substring(dt.LastIndexOf("/") + 1), "0", 4);


            if (Convert.ToInt32(part2) > 12) //it's a mm/dd/yyyy
                return part2 + "/" + part1 + "/" + part3;
            else
                return part1 + "/" + part2 + "/" + part3;

        }

        public static string GetDateMMDDYYY(string dt)
        {

            string part1;
            string part2;
            string part3;

            dt = dt.Contains(" ") ? dt.Substring(0, dt.IndexOf(" ")) : dt;
            dt = dt.Trim();

            part1 = LPad(dt.Substring(0, dt.IndexOf("/")), "0", 2);
            part2 = LPad(dt.Substring(dt.IndexOf("/") + 1, 2).Replace("/", ""), "0", 2);
            part3 = LPad(dt.Substring(dt.LastIndexOf("/") + 1), "0", 4);


            if (Convert.ToInt32(part1) > 12) //it's a dd/mm/yyyy
                return part2 + "/" + part1 + "/" + part3;
            else
                return part1 + "/" + part2 + "/" + part3;

        }

        public static string GetTimeFromNumbers(string t)
        {
            t = t.Trim();
            if (t.Length == 5)
            {
                t = t.Substring(0, 1) + ":" + t.Substring(1, 2) + ":" + t.Substring(3, 2);
            }
            else if (t.Length == 6)
            {
                //t = (Convert.ToInt32(t.Substring(0, 2)) > 23 ? "00" : t.Substring(0, 2)) + ":" + t.Substring(2, 2) + ":" + t.Substring(4, 2);
                t = t.Substring(0, 2) + ":" + t.Substring(2, 2) + ":" + t.Substring(4, 2);
            }
            return t;
        }


        #endregion

        #region Web Control Functions



        public static void SelectListItemByText(System.Web.UI.WebControls.ListControl List, string text)
        {
            System.Web.UI.WebControls.ListItem itm;
            itm = List.Items.FindByText(text);
            List.SelectedIndex = List.Items.IndexOf(itm);
        }

        public static void SelectListItem(System.Web.UI.WebControls.ListControl List, string value)
        {
            System.Web.UI.WebControls.ListItem itm;
            itm = List.Items.FindByValue(value);
            List.SelectedIndex = List.Items.IndexOf(itm);
        }

        public static void SelectListItem(System.Web.UI.WebControls.ListControl List, int value)
        {
            System.Web.UI.WebControls.ListItem itm;
            itm = List.Items.FindByValue(value.ToString());
            List.SelectedIndex = List.Items.IndexOf(itm);
        }

        public static void SelectListItem(System.Web.UI.WebControls.ListControl List, long value)
        {
            System.Web.UI.WebControls.ListItem itm;
            itm = List.Items.FindByValue(value.ToString());
            List.SelectedIndex = List.Items.IndexOf(itm);
        }

        public static void SelectListItem(System.Web.UI.HtmlControls.HtmlSelect List, string value)
        {
            System.Web.UI.WebControls.ListItem itm;
            itm = List.Items.FindByValue(value);
            List.SelectedIndex = List.Items.IndexOf(itm);

        }

        #endregion

        #region WebPage

        public static string GetRequestedVal(string requestVar, string alternateVal)
        {
            if (HttpContext.Current.Request[requestVar] == null) { return alternateVal; }
            string str = HttpContext.Current.Request[requestVar].ToString();
            return (!string.IsNullOrEmpty(str) ? str : alternateVal);

        }

        public static void ClearForm(System.Web.UI.Control ctrl, params System.Web.UI.Control[] exceptionalControls)
        {
            foreach (System.Web.UI.Control c in exceptionalControls)
            {
                if (ctrl.ID == c.ID)
                    return;
            }

            if (ctrl is TextBox)
            {
                ((TextBox)ctrl).Text = "";
            }
            else if (ctrl is CheckBox)
            {
                ((CheckBox)ctrl).Checked = false;
            }
            else if (ctrl is RadioButtonList)
            {
                ((RadioButtonList)ctrl).SelectedIndex = 0;
            }
            else if (ctrl is CheckBoxList)
            {
                ((CheckBoxList)ctrl).SelectedIndex = -1;
            }
            else if (ctrl is ListControl)
            {
                ((DropDownList)ctrl).SelectedIndex = -1;
            }

            foreach (System.Web.UI.Control c in ctrl.Controls)
            {
                ClearForm(c);
            }
        }


        public static void ClearForm(System.Web.UI.Control ctrl)
        {
            if (ctrl is TextBox)
            {
                ((TextBox)ctrl).Text = "";
            }
            else if (ctrl is CheckBox)
            {
                ((CheckBox)ctrl).Checked = false;
            }
            else if (ctrl is RadioButtonList)
            {
                ((RadioButtonList)ctrl).SelectedIndex = 0;
            }
            else if (ctrl is CheckBoxList)
            {
                ((CheckBoxList)ctrl).SelectedIndex = -1;
            }
            else if (ctrl is ListControl)
            {
                ((DropDownList)ctrl).SelectedIndex = -1;
            }
            else if (ctrl is ImageButton)
            {
                return;
            }
            else if (ctrl is Image)
            {
                ((Image)ctrl).ImageUrl = "~/images/noimage.jpg";
            }

            foreach (System.Web.UI.Control c in ctrl.Controls)
            {
                ClearForm(c);
            }
        }


        #endregion

        #region JavaScript

        public static void CreateConfirmBox(ref Button btn, string strMessage)
        {
            btn.Attributes.Add("onclick", "return confirm('" + strMessage + "');");
        }

        public static void CreateConfirmBox(ref LinkButton btn, string strMessage)
        {
            btn.Attributes.Add("onclick", "return confirm('" + strMessage + "');");
        }

        public static void CreateMessageAlert(System.Web.UI.Page aspxPage, string strMessage, string strKey)
        {
            string strScript = "<script language=JavaScript>alert('" + strMessage + "')</script>";

            if ((!aspxPage.ClientScript.IsStartupScriptRegistered(strKey)))
            {
                aspxPage.ClientScript.RegisterStartupScript(typeof(string), strKey, strScript);
            }
            //HttpContext.Current.Response.Write(strScript)
        }

        public static void CreatePopUpWindow(ref object sender, string url)
        {
            ((WebControl)sender).Attributes.Add("onclick", "window.open('" + url + "','_blank','width=450, height=450, left=200, top=50');");
            //SetFocus(btn.Parent, btn)
        }


        public static void RunJavaScript(System.Web.UI.Page aspxPage, string Script, string strKey)
        {
            string strScript = "<script language=JavaScript>" + Script + "</script>";

            if ((!aspxPage.ClientScript.IsStartupScriptRegistered(strKey)))
            {
                aspxPage.ClientScript.RegisterStartupScript(typeof(string), strKey, strScript);
            }
        }

        public static void SetFocusCtrl(ref System.Web.UI.Page aspxPage, System.Web.UI.Control ctrl)
        {
            string s = "<SCRIPT language='javascript'>document.getElementById('" + ctrl.ClientID + "').focus() </SCRIPT>";
            //aspxPage.ClientScript.RegisterStartupScript(typeof(string), "ctrlFocus", s);
            aspxPage.ClientScript.RegisterClientScriptBlock(typeof(string), "ctrlFocus", s);
        }

        public static void PageNavigation(ref System.Web.UI.Page aspxPage, string loc)
        {
            // Form the script to be registered at client side.
            string scriptString = "<script language=JavaScript>";
            scriptString += "location.href='#" + loc + "'";
            scriptString += "</script>";

        }


        public static void CloseWindow(System.Web.UI.Page AspxPage)
        {
            string strScript = "";
            strScript = "<script language=javascript>window.close();</script>";
            string strKey = "strKey";
            AspxPage.ClientScript.RegisterStartupScript("str".GetType(), strKey, strScript);

        }


        #endregion

        #region HTML

        private static string RemoveHTML(string Text)
        {
            if ((Text == null) || string.IsNullOrEmpty(Text))
                return "";

	    //global regex for all html tags= @"<(.|\n)*?>"
            System.Text.RegularExpressions.Regex RegEx = new System.Text.RegularExpressions.Regex("<[^>]*>");
            return RegEx.Replace(Text, "");
        }

        #endregion

        #region File Uploading
        #region File uploading helper functions

        // Function checks that either the filename has valid extension
        public static bool IsValidFileExtension(string sFile)
        {
            string ext = sFile.Substring(sFile.LastIndexOf(".") + 1);
            switch (ext.ToUpper())
            {
                case ".ZIP":
                case ".RAR":
                case ".DOC":
                case ".RTF":
                case ".XLS":
                case ".CSV":
                case ".HTM":
                case ".HTML":
                case ".PNG":
                case ".GIF":
                case ".JPG":
                case ".JPEG":
                case ".TIF":
                    return true;
                default:
                    return false;
            }
        }

        // Function checks that either the filename has valid Image extension
        public static bool IsValidImageFileExtension(string sFile)
        {
            string ext = sFile.Substring(sFile.LastIndexOf(".") + 1);
            switch (ext.ToUpper())
            {
                case ".JPG":
                case ".PNG":
                case ".GIF":
                case ".JPEG":
                case ".TIF":
                    return true;
                default:
                    return false;
            }
        }

        // The function checks either the file to be uploaded is valid
        public static bool IsValidFileToUpload(FileUpload file1, string ValidExtentions, int MaxFileSizeInMB)
        {
            //fileSize=10 i.e only the file smaller than 10 MB can be uploaded by Default

            //Checking for valid file

            if ((file1.PostedFile != null))
            {
                // PostedFile.FileName gives the entire path
                //Use Substring function to get the filename.
                string StrFileName = file1.PostedFile.FileName.Substring(file1.PostedFile.FileName.LastIndexOf("\\") + 1);

                //Get the type of the file
                string StrFileType = file1.PostedFile.ContentType;

                // Get size of uploaded file
                int IntFileSize = file1.PostedFile.ContentLength;

                if (!IsValidFileExtension(StrFileName))
                    throw new Exception("Not a valid file extension for current operation");

                //Checking for the file length 
                if (IntFileSize <= 0 | string.IsNullOrEmpty(StrFileName) | IntFileSize / 1024 / 1024 > MaxFileSizeInMB)
                {
                    throw new Exception("Invalid File Size or File Name");
                }
                else
                {
                    return true;
                }


            }
            else
                return false;

        }


        // Function checks that either the file has valid image extension
        public static bool IsValidImageExtension(string sFile)
        {
            string ext = sFile.Substring(sFile.LastIndexOf(".") + 1);

            string[] ValidExtensions = { "PNG", "GIF", "JPG", "JPEG", "TIF" };

            foreach (string str in ValidExtensions)
            {
                if (ext.ToUpper() == str)
                    return true;

            }

            return false;

        }


        // Function checks that either the file has valid image extension
        public static bool IsValidDocExtension(string sFile)
        {
            string ext = sFile.Substring(sFile.LastIndexOf(".") + 1);

            string[] ValidExtensions = { "DOC", "DOCX", "XSL", "XSLX", "PPS", "PPSX", "PDF", "TXT", "RTF" };

            foreach (string str in ValidExtensions)
            {
                if (ext.ToUpper() == str)
                    return true;

            }

            return false;

        }

        // The function checks either the image to be uploaded is valid
        public static bool IsValidImageFile(FileUpload file1, int MaxFileSizeInMB)
        {

            //Checking for valid file

            if ((file1.PostedFile != null))
            {
                // PostedFile.FileName gives the entire path
                //Use Substring function to get the filename.
                string StrFileName = file1.PostedFile.FileName.Substring(file1.PostedFile.FileName.LastIndexOf("\\") + 1);

                //Get the type of the file
                string StrFileType = file1.PostedFile.ContentType;

                // Get size of uploaded file
                int IntFileSize = file1.PostedFile.ContentLength;

                //check on uploaded file's extension. {currently this check is disabled}
                if ((IsValidImageExtension(StrFileName)))
                {

                    //Checking for the file length 
                    if (IntFileSize <= 0 | string.IsNullOrEmpty(StrFileName) | IntFileSize / 1024 / 1024 > MaxFileSizeInMB)
                    {
                        //If  IntFileSize <= 0 Or StrFileName = "" Or IntFileSize / 1024 / 1024 > MaxFileSize Then
                        throw new Exception("Not a valid File size or File name");
                    }
                    else
                    {
                        //File is valid
                        return true;
                    }
                }
                else
                {
                    throw new Exception("Invalid image extension to upload");
                }

            }

            return false;
        }

        // The function checks either the image to be uploaded is valid
        public static bool IsValidDocFile(FileUpload file1, int MaxFileSizeInMB)
        {

            //Checking for valid file

            if ((file1.PostedFile != null))
            {
                // PostedFile.FileName gives the entire path
                //Use Substring function to get the filename.
                string StrFileName = file1.PostedFile.FileName.Substring(file1.PostedFile.FileName.LastIndexOf("\\") + 1);

                //Get the type of the file
                string StrFileType = file1.PostedFile.ContentType;

                // Get size of uploaded file
                int IntFileSize = file1.PostedFile.ContentLength;

                //check on uploaded file's extension. {currently this check is disabled}
                if ((IsValidDocExtension(StrFileName)))
                {

                    //Checking for the file length 
                    if (IntFileSize <= 0 | string.IsNullOrEmpty(StrFileName) | IntFileSize / 1024 > MaxFileSizeInMB)
                    {
                        //If  IntFileSize <= 0 Or StrFileName = "" Or IntFileSize / 1024 / 1024 > MaxFileSize Then
                        throw new Exception("Not a valid File size or File name");
                    }
                    else
                    {
                        //File is valid
                        return true;
                    }
                }
                else
                {
                    throw new Exception("Invalid doc extension to upload");
                }

            }

            return false;
        }


        private static bool ThumbnailCallback()
        {
            return false;
        }

        //u can call this function as: SaveTNImage(100, 400, Me.File1.Value, "../images/tn/")
        private static bool SaveTNShotImage(int maxH, int maxW, string url, string DestinationFolder)
        {
            System.Drawing.Image thumbNailImg = null;
            System.Drawing.Image fullSizeImg = null;

            string FileName = null;
            int h = 0;
            int w = 0;
            int dif = 0;
            decimal ratio = default(decimal);

            try
            {
                fullSizeImg = System.Drawing.Image.FromFile(url);
            }
            catch
            {
                fullSizeImg = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(AppPath + "/images/noimage.jpg"));
            }


            FileName = url.Substring(url.LastIndexOf("\\") + 1);

            h = fullSizeImg.Height;
            w = fullSizeImg.Width;

            ratio = (decimal)((float)h / (float)w);
            w = maxW;
            h = (int)(ratio * maxW);
            if (h > maxH)
            {
                dif = h - maxH;
            }
            h = h - dif;
            w = (int)(h / ratio);
            if (w > maxW)
            {
                dif = w - maxW;
            }
            h = (int)(w * ratio);
            //Dim ht, wt As Unit

            //img.Width = 100 'wt.Parse(CStr(w))
            //img.Height = 100 'ht.Parse(CStr(h))

            System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = null;
            dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);

            thumbNailImg = fullSizeImg.GetThumbnailImage(w, h, dummyCallBack, IntPtr.Zero);

            //HttpContext.Current.Response.Write(FileName & "<BR>")
            //HttpContext.Current.Response.Write(url)


            try
            {
                System.IO.File.Delete(HttpContext.Current.Server.MapPath(DestinationFolder + "/tn/" + FileName));
                System.IO.File.Delete(HttpContext.Current.Server.MapPath(DestinationFolder + "/shot/" + FileName));

                thumbNailImg.Save(HttpContext.Current.Server.MapPath(DestinationFolder + "/tn/" + FileName));
                fullSizeImg.Save(HttpContext.Current.Server.MapPath(DestinationFolder + "/shot/" + FileName));

                thumbNailImg.Dispose();
                fullSizeImg.Dispose();
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Flush();
                System.IO.File.Delete(url);

            }
            catch (Exception ex)
            {
                thumbNailImg.Dispose();
                fullSizeImg.Dispose();
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Flush();
                System.IO.File.Delete(url);
                throw ex;
            }

            return true;

        }


        #endregion


        /// <summary>
        /// this function is used to upload an image from client to webserver on given remote path
        /// </summary>
        /// <param name="file"></param>
        /// <param name="RemotePath">RemotePath="../Images/CompanyLogos/"</param>
        /// <param name="NewFileName"></param>
        /// <param name="CreateTNShot"></param>
        /// <param name="tnMaxW"></param>
        /// <param name="tnMaxH"></param>
        /// <param name="maxSizeInMB"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static string UploadImage(FileUpload file, string RemotePath, string NewFileName, string defaultFileName, bool CreateTNShot, int tnMaxW, int tnMaxH, int maxSizeInMB, out string msg)
        {
            string functionReturnValue = defaultFileName;
            //e-g: LocalPath may be equal to HtmlFile.Value
            //e-g: RemotePath="../Images/CompanyLogos/"

            try
            {
                if (!IsValidImageFile(file, maxSizeInMB))
                    msg = "Not a valid image file to upload";
            }
            catch (Exception ex) { msg = ex.Message; return functionReturnValue; }

            try
            {
                int LastSlashIndex = 0;
                string fileName = null;
                string LocalPath = null;
                string FileFormat = null;
                string fileToSave = null;
                LocalPath = file.FileName;
                LastSlashIndex = LocalPath.LastIndexOf("\\");
                fileName = LocalPath.Substring(LastSlashIndex + 1);
                FileFormat = fileName.Substring(fileName.LastIndexOf(".") + 1);

                if (string.IsNullOrEmpty(NewFileName))
                {
                    fileToSave = RemotePath + fileName;
                    functionReturnValue = fileName;
                }
                else
                {
                    fileToSave = RemotePath + NewFileName + "." + FileFormat;
                    functionReturnValue = NewFileName + "." + FileFormat;
                }

                file.PostedFile.SaveAs(HttpContext.Current.Server.MapPath(fileToSave));
                file.PostedFile.InputStream.Dispose();

                if (CreateTNShot == true)
                {
                    SaveTNShotImage(tnMaxH, tnMaxW, HttpContext.Current.Server.MapPath(fileToSave), RemotePath);
                }


                //image successfully uploaded to specified location    
                msg = "Image saved successfully";

            }
            catch (Exception ex)
            {
                //image failed to upload on specified location    
                //Return "invalid"
                msg = ex.Message;
                throw new Exception(ex.Message);

            }

            return functionReturnValue;
        }


        /// <summary>
        /// Upload a file to destination
        /// </summary>
        /// <param name="File1"></param>
        /// <param name="ServerPath">serverPath can be "../images/logos/"</param>
        /// <param name="newName">if newName == "" then upload with default file name.</param>
        /// <returns></returns>
        public static bool UploadFile(FileUpload File1, string ServerPath, string newName)
        {
            string filename = File1.PostedFile.FileName;
            string ext = filename.Substring(filename.IndexOf("."));
            string StrFileName = newName == "" ? filename : newName;
            //Save file to disk
            File1.PostedFile.SaveAs(ServerPath + StrFileName + ext);
            return true;
        }

        #endregion

        #region "File Downloading"

        public static void DownloadFile(string fname, bool forceDownload)
        {
            string path = HttpContext.Current.Server.MapPath(fname);
            string name = System.IO.Path.GetFileName(path);
            string ext = System.IO.Path.GetExtension(path);
            string type = "";
            // set known types based on file extension  
            if (ext != null)
            {
                switch (ext.ToLower())
                {
                    //case ".htm":
                    //case ".html":
                    //    type = "text/HTML";
                    //    break;

                    //case ".txt":
                    //    type = "text/plain";
                    //    break;

                    //case ".doc":
                    //case ".rtf":
                    //    type = "Application/msword";
                    //    break;

                    case ".wmv":
                    case ".mpg":
                    case ".mpeg":
                    case ".avi":
                    case ".swf":
                        type = "video/mp4";
                        break;

                    case ".wma":
                    case ".mp3":
                        type = "audio/mp3";
                        break;

                    case ".jpg":
                    case ".jpeg":
                    case ".gif":
                    case ".png":
                        type = "image/jpeg";
                        break;
                        

                }
            }
            if (forceDownload)
            {
                HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename=" + name);
            }
            if (type != "")
                HttpContext.Current.Response.ContentType = type;
            HttpContext.Current.Response.WriteFile(path);
            HttpContext.Current.Response.End();
        }

        #endregion


        #region "This Website Funcs"

        public static void AddDateControlToPage(System.Web.UI.Page aspxPage)
        {
            Literal litCalendarScript = new Literal();
            litCalendarScript.Text = "" + (char)9;
            litCalendarScript.Text += "<link title='blue' href='" + AppPath + "/js/calendar/calendar-blue.css' media=all type='text/css' rel='Stylesheet' /> " + (char)9;
            litCalendarScript.Text += "<link title='system' href='" + AppPath + "/js/calendar/calendar-system.css' media='all' type='text/css' rel='stylesheet' />" + (char)9;

            litCalendarScript.Text += "<script language='javascript' src='" + AppPath + "/js/calendar/general.js' type='text/javascript'></script> " + (char)9;
            litCalendarScript.Text += "<script language='javascript' src='" + AppPath + "/js/calendar/calendar.js' type='text/javascript'></script> " + (char)9;
            litCalendarScript.Text += "<script language='javascript' src='" + AppPath + "/js/calendar/calendar-en.js' type='text/javascript'></script> " + (char)9;
            litCalendarScript.Text += "<script language='javascript' src='" + AppPath + "/js/calendar/calendar-nas.js' type='text/javascript'></script>" + (char)9;
            litCalendarScript.Text += "<script language='javascript' src='" + AppPath + "/js/calendar/disable_cr.js' type='text/javascript'></script> " + (char)9;
            //litCalendarScript.Text += "<script language='javascript' src='" & AppPath & "/scripts/general.js' type='text/javascript'></script> " & vbCrLf

            litCalendarScript.Text += "<!--start date check--> " + (char)9;
            litCalendarScript.Text += "<script type=\"text/javascript\"> " + (char)9;
            litCalendarScript.Text += "function checkDate(source, arguments) " + (char)9;
            litCalendarScript.Text += "{ " + (char)9;
            litCalendarScript.Text += "var txtResponse = isDate(arguments.Value); " + (char)9;
            litCalendarScript.Text += "if(txtResponse == \"\") " + (char)9;
            litCalendarScript.Text += "{ " + (char)9;
            litCalendarScript.Text += "    arguments.IsValid=true; " + (char)9;
            litCalendarScript.Text += "} " + (char)9;
            litCalendarScript.Text += " else " + (char)9;
            litCalendarScript.Text += "{ " + (char)9;
            litCalendarScript.Text += "    arguments.IsValid=false; " + (char)9;
            litCalendarScript.Text += "} " + (char)9;
            litCalendarScript.Text += "} " + (char)9;
            litCalendarScript.Text += "</script> " + (char)9;
            litCalendarScript.Text += "<!--end date check--> " + (char)9;

            aspxPage.Header.Controls.Add(litCalendarScript);

        }

        public static bool CheckFileAvailability(string fileNameWithPath)
        {
            if (fileNameWithPath == "")
                return false;

            return System.IO.File.Exists(HttpContext.Current.Server.MapPath(fileNameWithPath));
        }

        public static bool CheckVideoAvailability(string fileName)
        {
            if (fileName == "")
                return false;

            return System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/videos/" + fileName));
        }

        public static bool CheckRadioAvailability(string fileName)
        {
            if (fileName == "")
                return false;

            return System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/radio/" + fileName));
        }

        public static bool CheckCableAvailability(string fileName)
        {
            if (fileName == "")
                return false;

            //return System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/cable/" + fileName));
            return System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/radio/" + fileName));
        }


        public static bool CheckPressAvailability(string fileName)
        {
            if (fileName == "")
                return false;

            return System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/press/" + fileName));
        }
       
        public static bool CheckInternetAvailability(string fileName,string RFDate)
        {
            bool status=false;
            if (fileName == "")
                return false;
            RFDate = RFDate.Substring(0, 2);
            switch(RFDate)
            {
                case "1/":
                    status= System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/internet/January/" + fileName));
                    break;
                case "2/":
                    status = System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/internet/February/" + fileName));
                    break;
                case "3/":
                    status = System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/internet/March/" + fileName));
                    break;
                case "4/":
                    status = System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/internet/April/" + fileName));
                    break;
                case "5/":
                    status = System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/internet/May/" + fileName));
                    break;
                case "6/":
                    status = System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/internet/June/" + fileName));
                    break;
                case "7/":
                    status = System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/internet/July/" + fileName));
                    break;
                case "8/":
                    status = System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/internet/August/" + fileName));
                    break;
                case "9/":
                    status = System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/internet/September/" + fileName));
                    break;
                case "10":
                    status = System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/internet/October/" + fileName));
                    break;
                case "11":
                    status = System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/internet/November/" + fileName));
                    break;
                case "12":
                    status = System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/internet/December/" + fileName));
                    break;
            }
            return status;

        }

        public static bool CheckInternetAvailabilityNewsAlert(string fileName)
        {
            bool flag;
            bool flag1 = !(fileName == "");
            flag = (flag1 ? File.Exists(HttpContext.Current.Server.MapPath(string.Concat("~/NewsAlert/", fileName))) : false);
            return flag;
        }

        public static bool CheckOutDoorAvailability(string fileName)
        {
            if (fileName == "")
                return false;

            return System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/outdoor/" + fileName));
        }

        public static bool CheckOutDoorStreetAvailability(string fileName)
        {
            if (fileName == "")
                return false;

            return System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/outdoor-street/" + fileName));
        }


        public static string GetPressFile(DateTime rfDate, int mediaCode, int pressBodyCode, int pageNumber)
        {
            //in case of TT we need 3 digits of PageNumber
            //in other cases we need only 2 digits of pageNumber in the end of PRESS file names

            if(DefaultCountry==218)
                return rfDate.Year.ToString().Substring(2) + Utility.LPad(rfDate.Month.ToString(), "0", 2) + Utility.LPad(rfDate.Day.ToString(), "0", 2) + Utility.LPad(mediaCode.ToString(), "0", 2) +  pressBodyCode.ToString()  + Utility.LPad(pageNumber.ToString(), "0", 3) + ".JPG";
            else
                return rfDate.Year.ToString().Substring(2) + Utility.LPad(rfDate.Month.ToString(), "0", 2) + Utility.LPad(rfDate.Day.ToString(), "0", 2) + Utility.LPad(mediaCode.ToString(), "0", 2) +  pressBodyCode.ToString()  + Utility.LPad(pageNumber.ToString(), "0", 2) + ".JPG";

        }


        public static string GetCurrency(string amount)
        {
            switch (AppUser.GetCountry())
            {
                case 58:
                    {
                        return "RD$ " + amount;
                    }
                case 218:
                    {
                        return "TT$ " + amount;
                    }
                default:
                    {
                        return "RD$ " + amount;
                    }
            }
        }
        #endregion
        public static bool CheckVideoAvailabilityNewsAlert(string fileName)
        {
            if (fileName == "")
                return false;

            return System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/NewsAlert/" + fileName));
        }
        public static bool CheckRadioAvailabilityNewsAlert(string fileName)
        {
            if (fileName == "")
                return false;

            return System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/NewsAlert/" + fileName));
        }
        public static bool CheckPressAvailabilityNewsAlert(string fileName)
        {
            if (fileName == "")
                return false;

            return System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/NewsAlert/" + fileName));
        }


        public static string GetFormattedBoolID(string val, string trueText, string falseText)
        {
            if (System.Web.HttpContext.Current.Session["UserID"].ToString() == val)
            {
                return trueText;
            }
            else
                return falseText;
           
        }





    }//end class

}//end namespace